package cn.zebra.dev.common.utils;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.*;

/**
 * 实体类工具转换
 *
 * @author runnable@sina.cn
 */
public final class ObjectUtils {

    private static Map<String, Collection<Field>> classMap = new HashMap<>(64);

    /**
     * 实体对象转成Map - 缓存版本
     *
     * @param obj 实体对象
     */
    public static Map<String, Object> objectConvertMap(Object obj) {
        if (obj == null) {
            return new HashMap<>(2);
        }
        Class clazz = obj.getClass();
        String className = clazz.getName();
        Map<String, Object> map;
        if (classMap.containsKey(className)) {
            Collection<Field> fields = classMap.get(className);
            map = new HashMap<>(fields.size());
            try {
                for (Field field : fields) {
                    Object value = field.get(obj);
                    if (value != null && StrUtils.isNotBlank(value.toString())) {
                        map.put(field.getName(), value);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            Field[] fields = clazz.getDeclaredFields();
            map = new HashMap<>(fields.length);
            try {
                List<Field> fieldNames = new ArrayList<>(fields.length);
                for (Field field : fields) {
                    fieldNames.add(field);
                    field.setAccessible(true);
                    Object value = field.get(obj);
                    if (value != null && StrUtils.isNotBlank(value.toString())) {
                        map.put(field.getName(), value);
                    }
                }
                classMap.put(className, fieldNames);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return map;
    }

    /**
     * Map转成实体对象
     *
     * @param map   map实体对象包含属性
     * @param clazz 实体对象类型
     */
    public static <T> T mapConvertObject(Map<String, Object> map, Class<T> clazz) {
        if (map == null) {
            return null;
        }
        T obj = null;
        try {
            obj = clazz.newInstance();
            Field[] fields = obj.getClass().getDeclaredFields();
            for (Field field : fields) {
                int mod = field.getModifiers();
                if (Modifier.isStatic(mod) || Modifier.isFinal(mod)) {
                    continue;
                }
                field.setAccessible(true);
                field.set(obj, map.get(field.getName()));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return obj;
    }

}
